package org.xq.softcup.mq.remoting.invoker.router.impl;

import org.xq.softcup.mq.remoting.invoker.router.XQRpcLoadBalance;

import java.util.Random;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;

public class XQRpcLoadBalanceRoundStrategy extends XQRpcLoadBalance
{
    private ConcurrentHashMap<String, Integer> routeCountEachJob = new ConcurrentHashMap();
    private long CACHE_VALID_TIME = 0L;

    private int count(String serviceKey)
    {
        if (System.currentTimeMillis() > this.CACHE_VALID_TIME)
        {
            this.routeCountEachJob.clear();
            this.CACHE_VALID_TIME = (System.currentTimeMillis() + 86400000L);
        }
        Integer count = (Integer)this.routeCountEachJob.get(serviceKey);
        count = Integer.valueOf((count == null) || (count.intValue() > 1000000) ? new Random().nextInt(100) : (count = Integer.valueOf(count.intValue() + 1)).intValue());
        this.routeCountEachJob.put(serviceKey, count);
        return count.intValue();
    }

    public String route(String serviceKey, TreeSet<String> addressSet)
    {
        String[] addressArr = (String[])addressSet.toArray(new String[addressSet.size()]);


        String finalAddress = addressArr[(count(serviceKey) % addressArr.length)];
        return finalAddress;
    }
}
